import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController } from 'ionic-angular';
//充值
import { BalanceRechargePage } from '../balance-recharge/balance-recharge';
//完成
import { OrderComplatePage } from '../order-complate/order-complate';
//设置支付密码
import { SetpaypwdPage } from '../setpaypwd/setpaypwd';

import { Https } from '../../app/http.service'
/**
 * Generated class for the ConfirmOrderPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-confirm-order',
  templateUrl: 'confirm-order.html',
})
export class ConfirmOrderPage {
	balanceUrl = new Https().Url + "act=goods&op=app_my_balance";
	buyUrl = new Https().Url + "act=goods&op=buy_card";
	checkPwdUrl = new Https().Url + "act=goods&op=app_check_pay_pwd";
	goodsCount:number = 1;
	stock:number = 1;
	pay:number = 0;
	goodsPrice: number;
	priceCount:number;
	ssd = 'actived';
	balance: string;
	goodsId:string;
	goodsImg:string
	buyName:string
	goodsName: string
	//支付密码
	pwd = [];
	active = 0;
	pcactive:any;
	zhuanmai_rate:string;
	constructor(public navCtrl: NavController, public navParams: NavParams, public alertCtrl: AlertController ) {
		
		this.stock = this.navParams.get('num');
		this.goodsPrice = this.navParams.get('price');
		this.priceCount = this.goodsPrice;
		this.goodsId = this.navParams.get('id');
		this.goodsImg = this.navParams.get('img');
		this.buyName = this.navParams.get('buyname');
		this.goodsName = this.navParams.get('goodsname');
		this.zhuanmai_rate = this.navParams.get('zhuanmai_rate');
    }

    ionViewDidLoad() {
		console.log('ionViewDidLoad ConfirmOrderPage');
		let then = this
		fetch(this.balanceUrl, {
			method: "post",
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			body: "mid=" + localStorage.getItem("mid") + "&token=" + localStorage.getItem("token"),
		}).then((response) => {
			response.text().then((con) => {
				if (con != ''){
					let resource = JSON.parse(con);
					then.balance = resource['predeposit']
				}else{
					let confirm = then.alertCtrl.create({
						title: '温馨提示',
						message: "网络连接错误",
						buttons: [
							{ text: '确定' },

						]
					});
					confirm.present();
				}
				
			})
		}).catch((err) => {
			let confirm = then.alertCtrl.create({
				title: '温馨提示',
				message: err,
				buttons: [
					{ text: '确定' },

				]
			});
			confirm.present();
		})
	}
	goodsCut(num){
		//1: 增加,2:减少
		num == 1 ? this.goodsCount == this.stock ? this.goodsCount = this.stock : this.goodsCount++ : this.goodsCount == 1 ? this.goodsCount = 1 : this.goodsCount--;
		if (num == 1 && this.goodsCount <= this.stock){
			this.priceCount = this.goodsPrice * this.goodsCount
			this.priceCount = parseFloat(this.priceCount.toFixed(2));
		}else if(num == 0){
			this.priceCount > this.goodsPrice ? this.priceCount = this.priceCount - this.goodsPrice : this.priceCount = this.priceCount 
			this.priceCount = parseFloat(this.priceCount.toFixed(2));
		}
	}
	// 支付方法 payMethod
	payMode(num){
		this.pay = num
		console.log(this.pay);
	}
	confirmPay(){
		let then = this;		
		if (parseInt(localStorage.getItem("payPwd")) == 0 || localStorage.getItem("payPwd") == null){
			let confirm = then.alertCtrl.create({
				title: '温馨提示',
				message: "您尚未设置支付密码，请前往设置",
				buttons: [
					{ text: '确定',
						handler: () => {
							this.navCtrl.push(SetpaypwdPage)
						},
					},
					{ text:'取消' }
				]
			});
			confirm.present();
			return false;
		}
		let alert = this.alertCtrl.create({
			cssClass:" password ",
			enableBackdropDismiss:false,
		});

		alert.present(); 
		setTimeout(()=>{
			//弹窗主体
			let passPop = document.querySelector(".password>.alert-wrapper")
			//弹窗内容
			passPop.innerHTML = '<div class="pord" ><div class="title" ><img src="./assets/imgs/xx.png"></img><span>请输入支付密码</span></div><div class="hidden-pwd"  (keyup)="backkey(int,$event)" (keypress)="intkey(int,$event)"><input pattern="[0-9]*"  type="number" class="number"></div><div class="input" ><div class="pan" #int ><span contenteditable="true" ></span><span contenteditable="true" ></span><span contenteditable="true" ></span><span contenteditable="true" ></span><span contenteditable="true" ></span><span contenteditable="true" ></span></div><span class="remember"><a>忘记密码</a></span></div></div>'
			//获取关闭X的点击
			let close = document.querySelector(".password>.alert-wrapper>.pord>.title>img")
			//忘记密码
			let remember = document.querySelector(".password>.alert-wrapper>.pord>.input>.remember>a")
			//输入框
			let pwdInput = document.querySelector(".password>.alert-wrapper>.pord>.input>.pan")
			let pwdHiddenInput = document.querySelector(".password>.alert-wrapper>.pord>.hidden-pwd>input")
			
			close.addEventListener("click",()=>{
				//关闭弹窗
				this.pwd.splice(0, this.pwd.length)
				console.log(this.pwd)
				this.active = 0
				alert.dismiss();
			})
			remember.addEventListener("click",()=>{
				//忘记密码跳转
				console.log(remember)
			})
			pwdHiddenInput.addEventListener("keyup",(event:any)=>{
				// console.log(event.keyCode, 'keyCode')
				//输入密码
				if (event.keyCode == 8 && this.active != 0) {
					this.active = this.pwd.length - 1 <= 0 ? 0 : this.pwd.length - 1;
					if (this.active >= 0) {
						pwdInput.children[this.active].className = " "
						this.pwd.pop()
						if (this.pwd.length == 1) {
							this.pwd = []; 
							// this.active = 0;
						}
					}

				}
			})
			pwdHiddenInput.addEventListener("textInput", (event: any)=>{
				event.preventDefault();
				//输入密码
				// console.log(event.originalEvent.data.charCodeAt(),'keyCode')
				// console.log(event.data,'keyCode')
				// console.log(event.charCode,'charCode')
				// this.pwd[this.active] = String.fromCharCode(event.charCode)
				this.pwd[this.active] = event.data
				if (this.pwd.length == 6) {
					console.log(this.pwd);
					let pay = this.pwd[0] + this.pwd[1] + this.pwd[2];
					pwdInput.children[this.pwd.length - 1].className = "circle"
					fetch(this.checkPwdUrl,{
						method:"post",
						headers:{
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						body: "mid=" + localStorage.getItem("mid") + "&token=" + localStorage.getItem("token") + "&pay=" + pay + "&pwn=" + this.pwd[3] + this.pwd[4] + this.pwd[5],
					}).then((response)=>{
						response.text().then((json)=>{
							if (json != ''){
								let data = JSON.parse(json).datas;
								if(data.code == '0'){
									console.log(123)
									this.pwd = []
									then.paydy()
									this.active = 0
									alert.dismiss();
								}else{
									let confirm = then.alertCtrl.create({
										title: '温馨提示',
										message: "密码输入错误，请重新输入",
										buttons: [
											{ text: '确定' },

										]
									});
									confirm.present();
								}
							}else{
								let confirm = then.alertCtrl.create({
									title: '温馨提示',
									message: "网络连接错误，请重试",
									buttons: [
										{ text: '确定' },

									]
								});
								confirm.present();	
							}
						})
					}).catch((err)=>{
						let confirm = then.alertCtrl.create({
							title: '温馨提示',
							message: err,
							buttons: [
								{ text: '确定' },

							]
						});
						confirm.present();
					})

					
				} else if (this.pwd.length < 6) {
					pwdInput.children[this.pwd.length - 1].className = "circle"
					this.active++;
					this.pcactive = pwdInput.children[this.pwd.length];
					// this.pcactive.focus()
				}
			})
			
		},100)
		
	}

	paydy(){
		if (this.pay == 0){
			console.log(parseFloat(this.balance))
			if (parseFloat(this.balance)<= 0) {
				let confirm = this.alertCtrl.create({
					title: '温馨提示',
					message: '您的余额不够，请前往充值',
					buttons: [
						{text: '取消'},
						{
							text: '去充值',
							handler: () => {
								this.navCtrl.push(BalanceRechargePage)
							}
						}
					] 
				});
				confirm.present();
			} else {
				fetch(this.buyUrl + "&id=" + this.goodsId + "&num=" + this.goodsCount,{
					method:"post",
					headers:{
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					body: "mid=" + localStorage.getItem("mid") + "&token=" + localStorage.getItem("token"),

				}).then((response)=>{
					response.text().then((json)=>{
						let data = JSON.parse(json).datas;
						if (data['code'] == '3'){
							let confirm = this.alertCtrl.create({
								title: '温馨提示',
								message: '不能购买自己的商品',
								buttons: [
									{ text: '确定' },

								]
							}); 
							confirm.present();
						}else{
							this.navCtrl.pop();
							this.navCtrl.push(OrderComplatePage)
						}
						console.log(data);
					})
				}).catch((err)=>{
					alert(err);
				})

			}
		}
	}
}
